package com.katze.common.zip;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

public abstract class ZipCompressHandle<T> {

    protected Collection<Path> targets;

    protected Path storage;

    protected boolean isRoot = false;

    public ZipCompressHandle<T> target(Path target) {
        this.targets = Collections.singleton(target);
        this.storage = target.resolveSibling(target.getFileName() + ".zip");;
        return this;
    }

    public ZipCompressHandle<T> target(Collection<Path> targets) {
        this.targets = targets;
        Iterator<Path> iterator = targets.iterator();
        if (iterator.hasNext()){
            Path item = iterator.next();
            this.storage = item.resolveSibling(item.getFileName() + ".zip");
        }
        return this;
    }

    /**
     * 输出文件路径
     */
    public ZipCompressHandle<T> storage(Path storage) {
        this.storage = storage;
        return this;
    }

    /**
     * 压缩时是否包括父目录
     */
    public ZipCompressHandle<T> parent() {
        this.isRoot = true;
        return this;
    }

    /**
     * 遍历目录,并构建压缩对象
     */
    protected ScatterSample scatter() throws IOException {
        return ScatterSample.builder(isRoot).foreach(targets, (target)-> new ZipArchiveRequest(target, target.getFileName()));
    }

    /**
     * 构建压缩对象
     */
    public abstract T execute();

}
